Imports System
Imports System.IO
Imports System.Text
Imports System.Xml
Imports System.Xml.Serialization
Imports System.Reflection

''' <summary>
''' Methods to serialize and deserialize objects.
''' </summary>
Public Class SerializationUtil

#Region "Private constructor"

	Private Sub New()
		' Can't create instance!
	End Sub

#End Region

#Region "Methods"

	''' <summary>
	''' Gets the serialized UTF8 value for the specified object.
	''' </summary>
	''' <returns>The serialized XML string.</returns>
	Public Shared Function Serialize(ByVal obj As Object) As String

		Return Serialize(obj, Encoding.UTF8, GetType(Object).Name)

	End Function

	''' <summary>
	''' Gets the serialized value using the specified encoding and namespace.
	''' </summary>
	''' <returns>The serialized XML string.</returns>
	Public Shared Function Serialize(ByVal obj As Object, ByVal enc As Encoding, ByVal ns As String) As String

		Dim ms As New MemoryStream()
		Dim xs As New XmlSerializer(obj.GetType())
		Dim tw As New XmlTextWriter(ms, enc)

		xs.Serialize(tw, obj)

		ms = CType(tw.BaseStream, MemoryStream)

		Dim result As String = DataUtil.UTF8ByteArrayToString(ms.ToArray())

		ms.Dispose()

		Return result

	End Function

	''' <summary>
	''' Deserializes the xml using the specified type.
	''' </summary>
	''' <returns>The deserialized object.</returns>
	Public Shared Function Deserialize(ByVal xml As String, ByVal type As Type) As Object

		Return Deserialize(xml, type, Encoding.UTF8, type.Name)

	End Function

	''' <summary>
	''' Deserializes the xml using the specified type, encoding and namespace.
	''' </summary>
	''' <returns>The deserialized object.</returns>
	Public Shared Function Deserialize(ByVal xml As String, ByVal type As Type, ByVal enc As Encoding, ByVal ns As String) As Object

		If IOUtil.ValidatePhysicalPath(xml) Then
			xml = IOUtil.ReadFile(xml, enc)
		End If

		Dim xs As New XmlSerializer(type)
		Dim ms As New MemoryStream(DataUtil.StringToUTF8ByteArray(xml))
		Dim tw As New XmlTextWriter(ms, enc)
		Dim result As Object = xs.Deserialize(ms)

		ms.Dispose()

		Return result

	End Function

#End Region

	''' <summary>
	''' Copy basic properties from one object to another (does not work with complex data!)
	''' </summary>
	Public Shared Sub CopyObjectProperties(source As Object, target As Object)

		Dim infos As PropertyInfo() = target.GetType().GetProperties()

		For Each targetInfo As PropertyInfo In infos

			If targetInfo.CanWrite Then

				Dim sourceInfo As PropertyInfo = source.GetType().GetProperty(targetInfo.Name)

				If Not sourceInfo Is Nothing Then
					targetInfo.SetValue(target, sourceInfo.GetValue(source, Nothing), Nothing)
				End If

			End If

		Next

	End Sub

End Class